<?php

require_once('include/database/DBManagerFactory.php');

function generate_code($table_name, $column_name, $prefix = '', $seq_digits = 4) {
	$db = DBManagerFactory::getInstance();

	$len = strlen($prefix) + 1;

	$sql = "SELECT coalesce(max(cast(substring($column_name,$len) as unsigned)),0)+1 as seq FROM $table_name WHERE $column_name LIKE '$prefix%'";

	$result = $db->query($sql);
  $row  = $db->fetchByAssoc($result);

  if($row == null) {
		$number = str_pad(1, $seq_digits, "0", STR_PAD_LEFT);
	} else {
		$number = str_pad($row['seq'], $seq_digits, "0", STR_PAD_LEFT);
	}

	return $prefix . $number;
}

?>